package paperfly.game.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class MapSlicer {
	private String[] cordinates = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
	private File outputDirectory;
	private File inputFile;
	private int numberOfSlices;
	
	public MapSlicer(File input, File outputDir, int slices){
		if(!input.isFile() || !input.exists()){
			throw new RuntimeException("Can't slice the image.");
		}
		if(slices > cordinates.length){
			throw new RuntimeException("Can't slice in more than "+cordinates.length+" slices.");
		}
		setInputFile(input);
		setOutputDirectory(outputDir);
		setNumberOfSlices(slices);
	}

	public File getOutputDirectory() {
		return outputDirectory;
	}

	public void setOutputDirectory(File outputDirectory) {
		this.outputDirectory = outputDirectory;
		if(!outputDirectory.exists()){
			outputDirectory.mkdirs();
		}
	}

	public File getInputFile() {
		return inputFile;
	}

	public void setInputFile(File inputFile) {
		this.inputFile = inputFile;
	}

	public int getNumberOfSlices() {
		return numberOfSlices;
	}

	public void setNumberOfSlices(int numberOfSlices) {
		this.numberOfSlices = numberOfSlices;
	}
	
	public void slice(){
		BufferedImage fullMap = null;
		try {
			fullMap = ImageIO.read(inputFile);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		if(fullMap.getHeight() != fullMap.getWidth()){
			throw new RuntimeException("Image width != height");
		}
		int imWidth = fullMap.getWidth();

		int size = imWidth / numberOfSlices;
		
		for(int line = 0; line < numberOfSlices; line++){
			for(int column = 0; column < numberOfSlices; column++){
				BufferedImage quadrant = fullMap.getSubimage(column * size, line * size, size, size);
				try {
					ImageIO.write(quadrant, "jpeg", new File(getOutputDirectory().getAbsolutePath()+"/"+cordinates[line]+column+".jpg"));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		new MapSlicer(new File("images/maps/map1/full.bmp"),new File("images/maps/map1/slices"),8).slice();
	}
}
